package com.zzg.author.shrio.util;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import com.zzg.author.model.domain.SysUser;
import com.zzg.util.bean.BeanUtils;

/**
 * 获取当前用户信息
 * @author zzg
 *
 */

public class ShiroUtils {
	 private ShiroUtils(){
	        throw new IllegalStateException("Utility class");
	    }

	    private static Subject getSubject() {
	        return SecurityUtils.getSubject();
	    }

	    public static Session getSession() {
	        return SecurityUtils.getSubject().getSession();
	    }

	    public static void logout() {
	        getSubject().logout();
	    }

	    public static SysUser getSysUser() {
	        SysUser user = null;
	        Object obj = getSubject().getPrincipal();
	        if (ObjectUtils.allNotNull(obj)) {
	            user = new SysUser();
	            BeanUtils.copyBeanProp(user, obj);
	        }
	        return user;
	    }

	    public static void setSysUser(SysUser user) {
	        Subject subject = getSubject();
	        PrincipalCollection principalCollection = subject.getPrincipals();
	        String realmName = principalCollection.getRealmNames().iterator().next();
	        PrincipalCollection newPrincipalCollection = new SimplePrincipalCollection(user, realmName);
	        // 重新加载Principal
	        subject.runAs(newPrincipalCollection);
	    }

	 
}
